export const isDate = date => {
  if (date === null || date === undefined) return false;
  if (isNaN(new Date(date).getTime())) return false;
  if (Array.isArray(date)) return false; // deal with `new Date([new Date]) -> new Date()`
  return true;
};

export const toDate = date => {
  return isDate(date) ? new Date(date) : null;
};

export const isDateObject = val => val instanceof Date;

export const getDayCountOfMonth = (year, month) => {
  if (month === 3 || month === 5 || month === 8 || month === 10) {
    return 30;
  }
  if (month === 1) {
    if ((year % 4 === 0 && year % 100 !== 0) || year % 400 === 0) {
      return 29;
    } else {
      return 28;
    }
  }
  return 31;
};

export const getDayCountOfYear = year => {
  const isLeapYear = (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  return isLeapYear ? 366 : 365;
};

export const getFirstDayOfMonth = date => {
  const temp = new Date(date);
  temp.setDate(1);
  return temp.getDay();
};

export const prevDate = (date, amount = 1) => {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate() - amount);
};

export const nextDate = (date, amount = 1) => {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate() + amount);
};

export const getStartDateOfMonth = (year, month) => {
  const result = new Date(year, month, 1);
  const day = result.getDay();
  if (day === 0) {
    return prevDate(result, 7);
  }
  return prevDate(result, day);
};

export const clearTime = date => {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate());
};
